package com.gamer.p1.controller;

import com.gamer.p1.Response;
import com.gamer.p1.dto.LoginReq;
import com.gamer.p1.dto.SaveReq;
import com.gamer.p1.entity.DataEntity;
import com.gamer.p1.entity.UserEntity;
import com.gamer.p1.service.DataService;
import com.gamer.p1.util.AESUtil;
import com.gamer.p1.util.JsonUtils;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * @author 种鑫
 * @date 2024/2/2 9:55
 */
@RestController
@RequestMapping("p1")
public class DataController {
    @Resource
    DataService dataService;

    @GetMapping("/time")
    public Response time() {
        Map<String, Long> ts = Map.of("ts", System.currentTimeMillis());
        return Response.ok(ts);
    }

    @GetMapping("/loadData")
    public Response loadData(@RequestParam String uid,
                             @RequestParam String v,
                             @RequestParam Long ts) {
        DataEntity dataEntity = dataService.loadData(uid, v, ts);
        String s = JsonUtils.serializeToString(dataEntity);
        String encrypt = AESUtil.encrypt(s);
        return Response.ok(encrypt);
    }

    @GetMapping("/deleteData")
    public Response delData(@RequestParam String uid) {
        //  uid sdk获得
        dataService.delData(uid);
        return Response.ok("");
    }


    @PostMapping("saveData")
    public Response saveData(@RequestBody String data) {
//        String decrypt = AESUtil.decrypt(data);
//        SaveReq saveReq = JsonUtils.deserializeFromString(decrypt, SaveReq.class);
        SaveReq saveReq = JsonUtils.deserializeFromString(data, SaveReq.class);
        DataEntity dataEntity = dataService.saveData(saveReq);
        return Response.ok(dataEntity);
    }

    /**
     * 登录
     *
     * @param loginReq
     * @return
     */
    @Deprecated
    @PostMapping("login")
    public Response login(@RequestBody LoginReq loginReq) {
        Optional<UserEntity> user = dataService.findUser(loginReq);
        if (user.isPresent()) {
            return Response.ok(user.get());
        } else {
            return Response.ok("请先注册");
        }
    }

    /**
     * 注册
     *
     * @param loginReq
     * @return
     */
    @Deprecated
    @PostMapping("reg")
    public ResponseEntity reg(@RequestBody LoginReq loginReq) {
        UserEntity reg = dataService.reg(loginReq);
        if (reg == null) {
            return ResponseEntity.ok("用户已注册");
        } else {
            return ResponseEntity.ok(reg);
        }
    }
}
